package com.cwt_taxi_xa.custom_view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;

public class MarqueeText extends TextView implements Runnable {

	private final String TAG = "MarqueeText";

	private int currentScrollX; // 当前滚动的位置
	private boolean isStop = false;
	private int textWidth;
	private boolean isMeasure = false;
	private int scrollCount = 0;
	private OnScrollEndListener scrollEndListener;

	public MarqueeText(Context context) {
		super(context);
	}

	public MarqueeText(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public MarqueeText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		/**计算*/
		currentScrollX = -800;
		//		AppLog.i(TAG, "onMeasure");
	}

	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (!isMeasure) {
			getTextWidth();// 文字宽度只需要获取一次就可以了
			isMeasure = true;
		}
		//		AppLog.i(TAG, "onDraw");
	}

	private void getTextWidth() {
		Paint paint = this.getPaint();
		String str = this.getText().toString();
		textWidth = (int) paint.measureText(str);
		if(textWidth > this.getWidth()){
			textWidth = 800;
		}
		//		AppLog.i(TAG, "textWidth: "+textWidth);
	}

	@Override
	/*
	 * public void run() { currentScrollX-=2;//滚动速度.+号表示往左边-
	 * scrollTo(currentScrollX,0); if(isStop){ return; }
	 * if(getScrollX()<=-(this.getWidth())){ scrollTo(textWidth,0);
	 * currentScrollX=textWidth; } postDelayed(this, 5); }
	 */
	public void run() {
		currentScrollX += 2;// 滚动速度.+号表示往左边-
		scrollTo(currentScrollX, 0);
		if (isStop) {
			return;
		}
//		AppLog.i(TAG, "currentScrollX: "+currentScrollX+"; textWidth: "+textWidth);
		if (getScrollX() >= (textWidth)) {
			if(isMeasure){
				stopScroll();
			}
			/*currentScrollX = -(this.getWidth());// 当前出现的位置
			if(++scrollCount >= 3){
				stopScroll();
			}*/
		}
		postDelayed(this, 18);
	}

	// 开始滚动
	public void startScroll() {
		isStop = false;
		this.removeCallbacks(this);
		post(this);
	}

	// 停止滚动
	public void stopScroll() {
		isStop = true;
		scrollEndListener.stopScroll();
		destroyDrawingCache();
	}

	// 从头开始滚动
	public void startFromHead() {
		currentScrollX = 0;
		startScroll();
	}

	/**
	 * 设置滚动结束监听器
	 * @param listener 点击监听器实现类
	 */
	public void setOnScrollEndListener(OnScrollEndListener scrollEndListener) {
		this.scrollEndListener = scrollEndListener;
	}

	/**
	 * 点击监听器接口
	 * @author jason0539
	 *
	 */
	public interface OnScrollEndListener {
		public void stopScroll();
	}
}
